package com.example.cardgame

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.graphics.Color
import androidx.core.view.children
import com.example.cardgame.model.Card
import com.example.cardgame.model.CardMatchingGame
import com.example.cardgame.model.Deck

class MainActivity : AppCompatActivity(),View.OnClickListener {
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val girdLayout = findViewById<View>(R.id.gridLayout) as ViewGroup
        for (v in girdLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updataUI()

        val reset = findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updataUI()
        }
    }
    fun updataUI()
    {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.background)
            }
        }
        val score = findViewById<TextView>(R.id.score)
        score.text = String.format("%s%d", "Score: ", game.score)
    }

    override fun onClick(v: View?) {
        if(v is Button){
            val index=cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updataUI()
        }
    }
}

